package cn.tedu.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttProducer<T>{
    @Autowired
    private MqttClient mqttClient;
    @Autowired
    private MySerializer<T> mySerializer;
    /**
     * 发送消息
     * String topic: 主题
     * T message: 消息体
     * qos:默认 1
     * retain:默认 false
     */
    public boolean sendDefault(String topic,T message,int qos,boolean retain){
        try{
            mqttClient.publish(
                    topic,
                    mySerializer.serialize(message),
                    qos,
                    retain);
            return true;
        }catch (Exception e){
            log.error("发送消息失败",e);
        }
        return false;
    }
    //2.发送,利用至少一次,存储消息
    public boolean sendAtLeastOnceStored(String topic,T message){
        return this.sendDefault(topic,message,1,true);
    }
    //3.发送,至多一次 不存消息  绝对一次 存储消息
}
